<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
    <title></title>
</head>
<body>

<script>
  const data = {
    ok: true,
    text: 'hello world!'
  }

  function cleanup(effectFn) {
    for (let i = 0; i < effectFn.deps.length; i++) {
      effectFn.deps[i].delete(effectFn)
    }

    effectFn.deps.length = 0
  }

  let activeEffect
  const effect = (fn) => {
    const effectFn = () => {
      cleanup(effectFn)
      activeEffect = effectFn
      fn()
    }
    effectFn.deps = []
    effectFn()
  }

  const bucket = new WeakMap()

  function track(target, key) {
    if (!activeEffect) return
    let depsMap = bucket.get(target)
    if (!depsMap) {
      bucket.set(target, (depsMap = new Map()))
    }

    let deps = depsMap.get(key)
    if (!deps) {
      depsMap.set(key, (deps = new Set()))
    }
    deps.add(activeEffect)
    activeEffect.deps.push(deps)
  }

  function trigger(target, key) {
    const depsMap = bucket.get(target)
    if (!depsMap) {
      return
    }
    const effects = depsMap.get(key)
    const effectsToRun = new Set(effects)   // 防止死循环
    effectsToRun && effectsToRun.forEach(fn => fn())
  }

  const obj = new Proxy(data, {
    get(target, key) {
      track(target, key)
      return target[key]
    },
    set(target, key, newValue) {
      target[key] = newValue
      trigger(target, key)
      return true
    }
  })

  effect(function effectFn() {
    console.log('effect run')
    document.body.innerText = obj.ok ? obj.text : 'not'
  })

  setTimeout(() => {
    obj.ok = false
  }, 1000)

  setTimeout(() => {
    // effectFn不会执行
    obj.text = 'hello vue3!'
  }, 2000)

</script>
</body>
</html>
